import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout/Layout.vue'
import Login from '@/views/login/Index.vue'
import Home from '@/views/home/Home.vue'
//异步组件--懒加载
const Destination = () => import('@/views/destination/Destination.vue')
const SheQu = () => import('@/views/shequ/SheQu.vue')
//点击跳转同一个路径
// 在VueRouter上配置路由跳转，在router中的index.js中加上以下代码，注意加在use之前
const routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
    return routerPush.call(this, location).catch(err => {})
};


Vue.use(VueRouter)


const routes = [
  {
    path: '/',
    // name:'layout',
    component: Layout,
    //二级路由 
    children: [
      {
        path: '/',
        name: 'home',
        component: Home,
        meta: {
          isLogin: false
        }
      },
      {
        path: '/des',
        name: 'des',
        component: Destination,
        meta: {
          isLogin: true
        }
      },
      {
        path: '/shequ',
        name: 'shequ',
        component: SheQu,
        meta: {
          isLogin: true
        }
      },

    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  }
]

const router = new VueRouter({
  routes
})
//获取仓库token信息
import store from '@/store/index'
//vue组件：this.$store.state.xx.x

//路由全局前置守卫
router.beforeEach((to, from, next) => {
  console.log('to', to);
  //1. 判断进入当前的路由是否需要登录
  if (to.meta.isLogin) {//true 需要登录
    //2. 判断当前得用户是否登录 -- 身份标识 比如：username  token 
    let token = store.state.User.userinfo.token;
    if (token) {//登录过了
      next()
    } else {//token不存在或者过期了
      next('/login')
    }

  } else {
    //不需要登录 -- 可以直接进入路径界面
    next()
  }
})

export default router
